#include<iostream>
#include<cerrno>
#include<assert.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
using namespace std;

int main()
{
    int fds[2]={0};
    if(pipe(fds)==-1)
    {
        cout<<"pipefd[0]"<<fds[0]<<strerror(errno)<<endl;
        cout<<"pipefd[1]"<<fds[1]<<strerror(errno)<<endl;
    }

    pid_t id=fork();
    assert(id!=-1);
    if(id==0)
    {
        close(fds[0]);//关闭不需要的文件描述符
        string namestr="hello,我是子进程";
        int cnt =1;
        char buffer[1024];
        while(true)
        {
            snprintf(buffer,sizeof(buffer),"%s,计数器：%d,我的pid:%dgfgf",namestr.c_str(),cnt++,getpid());
            write(fds[1],buffer,strlen(buffer));
            sleep(10);
        }
        close(fds[1]);
       exit(0);
    }
    close(fds[1]);
    char buffer[1024];
    while(true)
    {
        int n=read(fds[0],buffer,sizeof(buffer)-1);//read不考虑读取的是什么，因为它是以字节流的形式读取，buffer最后一个位置保留，给'\0'
        if(n>0)
        {
            buffer[n]='\0';
            cout<<"i am father,chile give me message:"<<buffer<<endl;
        }
    
    
    }
    close(fds[0]);
    return 0;
}
